package com.ppt.android.common.di

import com.ppt.android.BuildConfig
import com.ppt.android.base.constant.VersionStatus
import com.ppt.android.base.utils.getAppVersionName
import com.ppt.android.common.constant.NetBaseUrlConstant
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.Level.BODY
import okhttp3.logging.HttpLoggingInterceptor.Level.NONE
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * 全局作用域的网络层的依赖注入模块
 *
 * @author ZouJiaCai
 * @since 6/4/21 8:58 AM
 */
@Module
@InstallIn(SingletonComponent::class)
class DINetworkModule {

    /**
     * [OkHttpClient]依赖提供方法
     *
     * @return OkHttpClient
     */
    @Singleton
    @Provides
    fun provideOkHttpClient(): OkHttpClient {

        // 日志拦截器部分
        val level = if (BuildConfig.VERSION_TYPE != VersionStatus.RELEASE) BODY else NONE
        val logInterceptor = HttpLoggingInterceptor().setLevel(level)

        val builder = OkHttpClient.Builder()
            .connectTimeout(15L * 1000L, TimeUnit.MILLISECONDS)
            .readTimeout(20L * 1000L, TimeUnit.MILLISECONDS)

        builder.addInterceptor(logInterceptor)
        /**
         * 统一添加token到请求头
         */
        builder.addInterceptor(Interceptor { chain ->
            val request = chain.request()
            val newBuilder = request.newBuilder()
            val version = getAppVersionName()
            val platform = "android"
            newBuilder.addHeader("version",""+ version)
            newBuilder.addHeader("platform","" + platform)

            chain.proceed(newBuilder.build())
        })


        builder.retryOnConnectionFailure(true)

        return builder.build()
    }

    /**
     * 项目主要服务器地址的[Retrofit]依赖提供方法
     *
     * @param okHttpClient OkHttpClient OkHttp客户端
     * @return Retrofit
     */
    @Singleton
    @Provides
    fun provideMainRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl(NetBaseUrlConstant.MAIN_URL)
            .addConverterFactory(GsonConverterFactory.create())//转换json
            .addConverterFactory(ScalarsConverterFactory.create())//转换文件流
            .client(okHttpClient)
            .build()
    }
}